/*
 * @Descripttion:
 * @version:
 * @Author: liwanpeng
 * @Date: 2020-12-02 09:55:07
 * @LastEditors: sueRimn
 * @LastEditTime: 2020-12-12 14:08:59
 */
;(function() {
  "use strict"
  var global = tinymce.util.Tools.resolve("tinymce.PluginManager")
  function selectLocalImages(editor) {
    var uploadurl = editor.getParam("images_upload_url", "", "string")
    var dom = editor.dom
    // 生成input输入框用于图片上传
    var input_f = $(
      '<input type="file" name="Filedata[]" accept="image/jpg,image/jpeg,image/png,image/gif" multiple="multiple">'
    )
    input_f.on("change", function(e) {
      var files = e.target.files || e.dataTransfer.files
      var file = files[0]
      // 限制图片大小
      var limitSize = editor
        .getParam("images_size_limt", "String")
        .replace(/[^0-9]/gi, "")
      var limitUnit = editor
        .getParam("images_size_limt", "String")
        .replace(/[^a-zA-Z]/g, "")
      var fileSize = readFileSizeUnit(file, limitUnit)
      if (Number(fileSize) > Number(limitSize)) {
        alert(
          "图片限制" +
            editor.getParam("images_size_limt", "String") +
            "以内,当前图片大小为" +
            fileSize +
            limitUnit +
            ",请裁剪图片。"
        )
        return
      }
      // base64位方式上传=====================start
      // var reader = new FileReader()
      // reader.readAsDataURL(file)
      // reader.onload = function() {
      //   editor.focus()
      //   editor.selection.setContent(
      //     dom.createHTML("img", { src: reader.result })
      //   )
      //   // console.log(reader.result) // 获取到base64格式图片
      // }
      // base64位方式上传=====================end

      /**
       * 此处代码为上传到后台的代码，当前版本只需base格式即可
       */
      var xhr
      xhr = new XMLHttpRequest()
      xhr.withCredentials = false
      xhr.open("POST", uploadurl)
      // 处理请求头
      var header = editor.getParam("uploadimage_header")
      for (var key in header) {
        // 遍历对象的所有属性
        xhr.setRequestHeader(key, header[key])
      }
      xhr.onload = function() {
        var json
        if (xhr.status !== 200) {
          alert("HTTP Error: " + xhr.status)
          return
        }
        json = JSON.parse(xhr.responseText)
        if (!json || json.errno !== 0) {
          alert("Invalid JSON: " + xhr.responseText)
          return
        } else {
          editor.focus()
          json.data.forEach(function(path) {
            editor.selection.setContent(dom.createHTML("img", { src: path }))
          })
        }
      }
      var formData = new FormData()
      formData.append("file", file, file.name)
      // 处理额外参数
      var extraParam = editor.getParam("extrta_param")
      for (var key in extraParam) {
        // 遍历对象的所有属性
        formData.append(key, extraParam[key])
      }
      xhr.send(formData)
    })

    input_f.click()
  }

  var register$1 = function(editor) {
    editor.ui.registry.addButton("uploadimage", {
      icon: "image",
      tooltip: "上传图片",
      onAction: function() {
        selectLocalImages(editor)
      }
    })
    editor.ui.registry.addMenuItem("uploadimage", {
      icon: "image",
      text: "上传图片",
      onAction: function() {
        selectLocalImages(editor)
      }
    })
  }
  var Buttons = { register: register$1 }
  function Plugin() {
    global.add("uploadimage", function(editor) {
      Buttons.register(editor)
    })
  }
  function readFileSizeUnit(file, unit) {
    let UNITS = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
    let STEP = 1024
    let size = file.size
    var value = parseFloat(size, 10)
    var unitIndex = UNITS.indexOf(unit)
    if (unitIndex <= -1) {
      return -1
    } else if (unitIndex > 0) {
      return (value / Math.pow(STEP, unitIndex)).toFixed(2)
    }
  }
  function getImgToBase64(url, callback) {
    // 将图片转换为Base64
    var canvas = document.createElement("canvas")
    var ctx = canvas.getContext("2d")
    var img = new Image()
    img.crossOrigin = "Anonymous"
    img.onload = function() {
      canvas.height = img.height
      canvas.width = img.width
      ctx.drawImage(img, 0, 0)
      var dataURL = canvas.toDataURL("image/png")
      callback(dataURL)
      canvas = null
    }
    img.src = url
  }
  Plugin()
})()
